// pages/step/step.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    auth: false,
    url: app.globalData.url,
    userInfo: {},
    runData: '',
    todayRun: null,
    target: null,
    user: null,
    userStepsInfo: {},
    hasUser: false,
    orders: [],
    hasUserInfo: false,
    hasRunData: false,
    hasUserStepsInfo: false,
    hiddenStep: true,
    hiddenCoin: true,
    hasOrders: false,
    show: true,
    currenyText: true,
    hide: 0
  },
  handlerUser:function(res){
      var userInfo = res.detail.userInfo;
      app.toAuth(userInfo);
  },
  gotoSetStep: function () {
    wx.switchTab({
      url: '/pages/mine/mine'
    })
  },
  currenyText: function () {
    this.setData({
      currenyText: false
    });
  },
  confirm: function () {
    this.setData({
      currenyText: true
    });
  },
  openConfirm: function () {
    var self = this;
    wx.showModal({
      title: '兑换运动币',
      content: '兑换运动币比例 5000步：1个，当日只可兑换一次,截止当日22点30分，每日上限为6个，过期作废',
      confirmText: "确认",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          var threeSession = app.get3Session();
          wx.request({
            url: app.globalData.domain + '/step/exchangeCurreny?threeSession=' + threeSession,
            data: {
              threeSession: threeSession,
            },
            dataType: 'json',
            success: function (data) {
              var msg = data.data;
              if (msg == 'fail') {
               self.showFail();
              }else if (msg == 'notime') {
                self.showFail();
              } else {
                self.showSuccess(msg);
                self.setData({
                  todayRun: { currency: 1 },
                  show: false
                });
                self.getUserAgain(threeSession);
              }
            }
          })
        }
      }
    });
  },
  showFail: function () {
    wx.showModal({
      title: '兑换失败',
      content: '当日兑换截止时间为22点30分，过期作废',
      confirmText: "关闭",
      showCancel:false,
      success: function (res) {
        if (res.confirm) {
        }
      }
    });
  },
  showSuccess:function(msg){
    wx.showModal({
      title: '兑换成功',
      content: msg,
      confirmText: "关闭",
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          // var threeSession = app.get3Session();
          // self.getUserAgain(threeSession);
        }
      }
    });
  },
  getUserAgain: function (threeSession) {
    var self = this;
    wx.request({
      url: app.globalData.domain + 'user/mine?threeSession=' + threeSession,
      dataType: 'json',
      success: function (data) {
        if (data.data.user == '') {
          return;
        }
        self.setData({
          user: data.data.user
        });
        app.globalData.user = data.data.user;
      }
    })
  },
  setAuth: function (e) {
    app.stepAuthReadyCallback = res => {
      this.setData({
        auth: true
      })
    }
  },
  onShow: function () {
    var self = this;
    // app.get3Session();
    if (this.data.hide == 0 || wx.getStorageSync('threeSession') == null || wx.getStorageSync('threeSession') == '' || wx.getStorageSync('threeSession') == undefined) {
      // app.toAuth();
      this.setData({
        hide: this.data.hide + 1
      })
    }
    this.setAuth();
    if (app.globalData.authUser && app.globalData.authRun) {
      this.setData({
        auth: true
      });
    }
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      });
    } else {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    }
    if (app.globalData.todayRun) {
      this.setData({
        todayRun: app.globalData.todayRun
      });
    } else {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.todayRunReadyCallback = res => {
        this.setData({
          todayRun: res
        })
      }
    }
    if (app.globalData.runData) {
      this.setData({
        runData: app.globalData.runData,
        hasRunData: true
      });
    } else {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.runDataReadyCallback = res => {
        this.setData({
          runData: app.globalData.runData,
          hasRunData: true
        })
      }
    }
    if (app.globalData.target) {
      this.setData({
        target: app.globalData.target,
        hasTarget: true
      });
    } else {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.targetReadyCallback = res => {
        this.setData({
          target: res.data,
          hasTarget: true
        })
      }
    }
    if (app && app.globalData.createUser && app.getOrders && !app.globalData.isSearchOrder) {
      app.getOrders(app.get3Session(), 0, true);
    }
    //排名
    if (app.globalData.orders.length > 0) {
      var self = this;
      var temps = [];
      for (var k = 0, length = app.globalData.orders.length; k < length; k++) {
        temps.push(app.globalData.orders[k]);
      }
      this.setData({
        orders: temps,
        hasOrders: true
      });
    } else {
      var self = this;
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.stepOrdersReadyCallback = res => {
        var temps = [];
        for (var k = 0, length = res.data.length; k < length; k++) {
          temps.push(res.data[k]);
        }
        var sorted = temps;
        var result = temps.splice(0, 1);
        var compare = function compare(property) {
          return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            return value1 - value2;
          }
        }
        sorted.sort(compare('no'))
        this.setData({
          orders: result.concat(sorted),
          hasOrders: true
        })
      }
      app.stepSecondOrdersReadyCallback = res => {
        var temps = self.data.orders;
        for (var k = 0, length = res.data.length; k < length; k++) {
          temps.push(res.data[k]);
        }
        var sorted = temps;
        var result = temps.splice(0, 1);
        var compare = function compare(property) {
          return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            return value1 - value2;
          }
        }
        sorted.sort(compare('no'))
        this.setData({
          orders: result.concat(sorted),
          hasOrders: true
        })
      }
    }
    //用户信息
    if (app.globalData.user) {
      self.setData({
        user: app.globalData.user,
        hasUser: true
      });
    } else {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userReadyCallback = res => {
        if (res != null && res.data != null && res.data.user != null) {
          self.setData({
            user: res.data.user,
            hasUser: true
          })
        }
      }
    }
    if (app.globalData.userStepsInfo) {
      this.setData({
        userStepsInfo: app.globalData.userStepsInfo,
        hasUserStepsInfo: true
      });
    } else {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userStepInfoReadyCallback = res => {
        this.setData({
          userStepsInfo: res.data,
          hasUserStepsInfo: true
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  onHide: function () {
    app.globalData.orders = [];
    app.globalData.isSearchOrder = false;
    app.globalData.length=0;
    this.setData({
      orders: [],
      hasOrders: false
    });
  },
  onReachBottom: function (options) {
    const app = getApp();
    if (app.globalData.isSearchOrder) {
      wx.hideLoading();
      return
    }
    var threeSession = app.get3Session();
    var length = app.globalData.length;
    wx.showLoading({
      title: '加载中',
    });
    app.getOrders(threeSession, (length-1), false);
  },
  onShareAppMessage: function (ops) {
    if (ops.from === 'button') {
      // 来自页面内转发按钮
    }
    return {
      title: 'MEDATA',
      path: 'pages/step/step',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  setStep: function (e) {
    const threeSession = app.get3Session();
    wx.request({
      url: app.globalData.domain + 'wechat/user/setTarget?threeSession=' + threeSession,
      data: {
        threeSession: threeSession,
        types: 'step',
        value: e.detail.value
      },
      dataType: 'json',
      success: function (data) {
      }
    })
  },
})